package org.kinglone.back.user.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.kinglone.back.user.model.User;
import org.kinglone.common.dao.impl.BaseDaoImpl;
import org.kinglone.common.util.MD5;
import org.kinglone.common.util.PageQuery;
import org.kinglone.common.util.PageResults;
import org.kinglone.common.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("userService")
@Transactional(readOnly=false)
public class UserServiceImpl extends BaseDaoImpl<User> implements UserService{

	//登录
	@Override
	public User findUserInfo(User user) {
		try {
		String hql = "from User u where u.username = ? and u.password = ?";		
		Object[] queryParamMap = new Object[]{user.getUsername(),MD5.getMD5(user.getPassword())};		
			User userInfo = super.getByHQL(hql, queryParamMap);	
			return userInfo;			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	//分页查询用户列表
	@Override
	public PageResults<User> findUserList(PageQuery pageQuery,String name,String phone) {
		StringBuffer hql = new StringBuffer("from User u where 1=1 ");
		StringBuffer whereHql = new StringBuffer();
		Map<String, Object> queryParamMap = new HashMap<String, Object>();
		// 姓名
	if (!StringUtil.isNullOrEmpty(name)) {
			whereHql.append(" and username like :name");
			queryParamMap.put("name", '%'+ name +'%');
		}
		//手机
		if (!StringUtil.isNullOrEmpty(phone)) {
			whereHql.append(" and phone like :phone");
			queryParamMap.put("phone",'%'+phone +'%');
		}
		StringBuffer countsql = new StringBuffer(" select count(0) from user where 1=1 ");
		PageResults<User> pageResults = super.findPageByHqlAndCountSql(hql.append(whereHql).toString(),countsql.append(whereHql).toString(),pageQuery, queryParamMap, queryParamMap);
		return pageResults;
	}

	//根据用户名查询用户
	@Override
	public User findUserByUsername(String username) {
		String hql = "from User u where u.username = ? ";
		Query query = this.getSession().createQuery(hql);
		query.setParameter(0,username);
		List<User> list = query.list();
		if(list.size() > 1){
			User user = list.get(0);
			return user;
		}else{
			return null;
		}
	}

}
